import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import { omit, cloneDeep } from 'lodash'
import {
  generateRoutesByServer,
  flatMultiLevelRoutes,
  removeButtonMenu
} from '@/utils/router-helper'
import { store } from '../index'

// // 简单版 deepClone（替代 lodash-es 的 cloneDeep）
// function deepClone(obj) {
//   return JSON.parse(JSON.stringify(obj))
// }

export const usePermissionStore = defineStore('permission', {
  state: function () {
    return {
      routers: [],
      addRouters: [],
      isAddRouters: false,
      menuTabRouters: []
    }
  },
  getters: {
    getRouters: function () {
      return this.routers
    },
    getAddRouters: function () {
      //扁平化
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters: function () {
      return this.isAddRouters
    },
    getMenuTabRouters: function () {
      return this.menuTabRouters
    }
  },
  actions: {
    //生成动态路由
    generateRoutes: function (type, routers) {
      return new Promise((resolve) => {
        let routerMap = []
        if (type === 'server') {
          routerMap = generateRoutesByServer(routers)
        } else if (type === 'frontEnd') {
          // routerMap = generateRoutesByFrontEnd(deepClone(asyncRouterMap), routers)
        } else {
          routerMap = deepClone(asyncRouterMap)
        }
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        //静态路由 + 动态路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        resolve()
      })
    },

    setIsAddRouters: function (state) {
      this.isAddRouters = state
    },

    setMenuTabRouters: function (routers) {
      this.menuTabRouters = routers
    }
  },
  persist: [
    {
      pick: ['routers'],
      storage: localStorage
    },
    {
      pick: ['addRouters'],
      storage: localStorage
    },
    {
      pick: ['menuTabRouters'],
      storage: localStorage
    }
  ]
})

export function usePermissionStoreWithOut() {
  return usePermissionStore(store)
}
